# -*- coding: utf-8 -*-
"""
Created on Mon Nov 16 10:29:20 2020

@author: xyz

存放xpose界面的函数

"""

#必备的包
import sys
import os
from PyQt5.QtWidgets import QWidget, QApplication, QFileDialog, QMessageBox
from PyQt5.QtCore import Qt
from fit import Fit
#fit界面的其他子界面
from window import MainWin
#nlmixr的包
from nlmixr import *

class VisualPlot(MainWin):
    def __init__(self):
        super().__init__()
        self.plot_list_in_visual = []
        #获取globalenv的按钮
        self.pushButton_2.clicked.connect(self.get_globalenv_in_visual)
        self.pushButton_2.clicked.connect(self.display_globalenv_in_visual)
        #获取选中变量的按钮 self.global_var_in_visual是最终返回的被选中的var
        self.pushButton_3.clicked.connect(self.get_contents_in_lineEdit)
        #选中某个功能
        self.dv_vs_pred.stateChanged.connect(self.choose_dv_vs_pred)
        self.dv_vs_ipred.stateChanged.connect(self.choose_dv_vs_ipred)
        self.res_vs_idv.stateChanged.connect(self.choose_res_vs_idv)
        self.res_vs_pred.stateChanged.connect(self.choose_res_vs_pred)
        #作图
        self.pushButton.clicked.connect(self.plot_it_in_visual)
        
    def get_globalenv_in_visual(self):
        #获取globalenv中的变量
        glonames = robjects.r.ls(globalenv)
        self.globalnames = []
        for x in glonames:
            self.globalnames.append(x)
        
    def display_globalenv_in_visual(self):
        #显示globalenv中的变量
        self.textBrowser.setText('')
        for x in self.globalnames:
            self.textBrowser.append(x)
    
    def get_contents_in_lineEdit(self):
        #获取从lineEdit输入的内容
        self.global_var_in_visual = self.lineEdit.text()
        # print(type(self.global_var_in_visual))
        QMessageBox.information(self,'提示','获取成功！',QMessageBox.Ok,QMessageBox.Ok)
        return self.global_var_in_visual

    def choose_dv_vs_pred(self, state):
        #当选择了dv_vs_pred按钮，将dv_vs_pred添加到需要绘制图表的列表里
        if state == Qt.Checked:
            self.plot_list_in_visual.append('dv_vs_pred')
            # print(self.plot_list_in_visual)
        else:
            self.plot_list_in_visual.remove('dv_vs_pred')
            # print(self.plot_list_in_visual)
            
    def choose_dv_vs_ipred(self, state):
        if state == Qt.Checked:
            self.plot_list_in_visual.append('dv_vs_ipred')
            # print(self.plot_list_in_visual)
        else:
            self.plot_list_in_visual.remove('dv_vs_ipred')
            # print(self.plot_list_in_visual)
            
    def choose_res_vs_idv(self, state):
        if state == Qt.Checked:
            self.plot_list_in_visual.append('res_vs_idv')
            # print(self.plot_list_in_visual)
        else:
            self.plot_list_in_visual.remove('res_vs_idv')
            # print(self.plot_list_in_visual)
            
    def choose_res_vs_pred(self, state):
        if state == Qt.Checked:
            self.plot_list_in_visual.append('res_vs_pred')
            # print(self.plot_list_in_visual)
        else:
            self.plot_list_in_visual.remove('res_vs_pred')
            # print(self.plot_list_in_visual)
    
    def plot_it_in_visual(self):
        self.pushButton.setEnabled(False)
        #用visual界面绘图
        l = []
        robjects.r('''xp.%s <- xpose_data_nlmixr(%s, xp_theme = theme_xp_nlmixr())''' %(self.global_var_in_visual,self.global_var_in_visual))
        if 'dv_vs_pred' in self.plot_list_in_visual:
             xp1 = robjects.r('''xp1 <- dv_vs_pred(xp.%s, title = "DV vs PRED",
                   subtitle = NULL, caption = NULL) +
   coord_cartesian(ylim=c(0,1000), xlim=c(0,1000)) +
   scale_x_continuous("Population predictions") +
   scale_y_continuous("Observed concentrations")''' %self.global_var_in_visual)
             l.append('xp1,')
        else:
            l.append('')
  
        if 'dv_vs_ipred' in self.plot_list_in_visual:
            xp2 = robjects.r('''xp2 <- dv_vs_ipred(xp.%s, title = "DV vs IPRED",
                   subtitle = NULL, caption = NULL) +
  coord_cartesian(ylim=c(0,1000), xlim=c(0,1000))+
  scale_x_continuous("Individual predictions") +
  scale_y_continuous("Observed concentrations")''' %self.global_var_in_visual)
            l.append('xp2,')
        else:
            l.append('')
  
        if 'res_vs_idv' in self.plot_list_in_visual:
            xp3 = robjects.r('''xp3 <- res_vs_idv(xp.%s, res = "CWRES", title = "CWRES vs time",
                  subtitle = NULL, caption = NULL) +
  coord_cartesian(ylim=c(-3.5,3.5)) +
  scale_x_continuous("Time (h)") +
  scale_y_continuous("Conditional weighted residuals")''' %self.global_var_in_visual)
            l.append('xp3,')
        else:
            l.append('')
  
        if 'res_vs_pred' in self.plot_list_in_visual:
            xp4 = robjects.r('''xp4 <- res_vs_idv(xp.%s, res = "CWRES", title = "CWRES vs time",
                  subtitle = NULL, caption = NULL) +
  coord_cartesian(ylim=c(-3.5,3.5)) +
  scale_x_continuous("Time (h)") +
  scale_y_continuous("Conditional weighted residuals")''' %self.global_var_in_visual)
            l.append('xp4,')
        else:
            l.append('')

        #将xp1至xp4绘制在一个pdf中
        pdf("fig1_%s.pdf" %self.global_var_in_visual ,width=8,height=8)
        robjects.r('''grid.arrange(%s%s%s%s nrow=2)'''%(l[0],l[1],l[2],l[3]))
        dev_off()
        self.pushButton.setEnabled(True)
        QMessageBox.information(self,'提示','已保存至当前工作目录下',QMessageBox.Ok,QMessageBox.Ok)
